using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IniParser;
using IniParser.Model;
using System.Linq;

namespace WINPE_TOOLBOX
{
    public static class Utils
    {
        // 解析 JSON 文件
        public static T ParseJsonFile<T>(string path)
        {
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(path));
        }

        // 写入 JSON 文件
        public static void WriteJsonFile(string path, object jsonData)
        {
            File.WriteAllText(path, JsonConvert.SerializeObject(jsonData, Formatting.Indented));
        }

        // 判断字符串是否为 JSON 格式
        public static bool IsJson(string str)
        {
            try
            {
                var obj = JsonConvert.DeserializeObject<object>(str);
                return obj != null;
            }
            catch
            {
                return false;
            }
        }

        // 读取 HotPE 配置
        public static IniData ReadHotPEConfig(string drive)
        {
            var parser = new FileIniDataParser();
            return parser.ReadFile($"{drive.Substring(0, 1)}:\\HotPE\\confi.ini");
        }

        // 保存 HotPE 配置
        public static void WriteHotPEConfig(string drive, IniData data)
        {
            var parser = new FileIniDataParser();
            parser.WriteFile($"{drive.Substring(0, 1)}:\\HotPE\\confi.ini", data);
        }

        // 判断是否为 HotPE 盘
        public static bool IsHotPEDrive(string drive)
        {
            return File.Exists($"{drive.Substring(0, 1)}:\\HotPE\\confi.ini") &&
                   Directory.Exists($"{drive.Substring(0, 1)}:\\HotPEModule\\");
        }

        // 判断文件是否存在
        public static bool IsFileExisted(string path)
        {
            return File.Exists(path);
        }

        // 处理命令行参数：含 空或&或, 字符串加引号
        public static string DealStrForCmd(string str)
        {
            if (str.Contains(" ") || str.Contains("&") || str.Contains(","))
            {
                return $"\"{str}\"";
            }
            return str;
        }

        // 取字符串中间
        public static string TakeMidStr(string str, string leftStr, string rightStr)
        {
            int start = str.IndexOf(leftStr) + leftStr.Length;
            int end = str.IndexOf(rightStr, start);
            return str.Substring(start, end - start);
        }

        // 取字符串左边
        public static string TakeLeftStr(string str, string taggedStr)
        {
            return str.Substring(0, str.IndexOf(taggedStr));
        }

        // 取字符串右边
        public static string TakeRightStr(string str, string taggedStr)
        {
            return str.Substring(str.IndexOf(taggedStr) + taggedStr.Length);
        }

        // 删除数组中的空值
        public static List<string> FilterArrayNull(List<string> arr)
        {
            return arr.FindAll(s => !string.IsNullOrWhiteSpace(s));
        }

        // 遍历文件
        public static async Task<List<string>> TraverseFiles(string directoryPath, string extension = "")
        {
            if (!Directory.Exists(directoryPath))
            {
                Console.Error.WriteLine("Directory does not exist.");
                return new List<string>();
            }

            try
            {
                return await Task.Run(() =>
                {
                    // Get all files with the specified extension
                    var files = Directory.GetFiles(directoryPath, $"*{extension}", SearchOption.TopDirectoryOnly).ToList();
                    return files;
                });
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error retrieving files: " + ex.Message);
                return new List<string>();
            }
        }

        // 复制文件
        public static bool CopyFile(string path, string toPath)
        {
            if (path != toPath)
            {
                try
                {
                    File.Copy(path, toPath, true);
                    return true;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex);
                    return false;
                }
            }
            return true;
        }

        // 复制目录
        public static bool CopyDir(string path, string toPath)
        {
            try
            {
                foreach (string dirPath in Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(path, toPath));
                }

                foreach (string newPath in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(path, toPath), true);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 删除文件
        public static bool DelFiles(string path)
        {
            try
            {
                File.Delete(path);
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 删除目录
        public static bool DelDir(string path)
        {
            try
            {
                Directory.Delete(path, true);
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 移动文件
        public static bool MoveFiles(string path, string toPath)
        {
            try
            {
                File.Move(path, toPath);
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 创建目录
        public static bool MakeDir(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 文件重命名
        public static bool ReNameFile(string filePath, string newFilePath)
        {
            try
            {
                File.Move(filePath, newFilePath);
                return true;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                return false;
            }
        }

        // 格式化文件大小
        public static string FormatSize(long v)
        {
            string[] UNITS = { "B", "KB", "MB", "GB", "TB", "PB", "ZB" };
            int i = 0;
            double prev = 0;
            while (v > 0 && i < UNITS.Length)
            {
                prev = v;
                v /= 1024;
                i++;
            }

            if (i > 0 && i < UNITS.Length)
            {
                v = (long)prev;
                i--;
            }
            return Math.Round((double)v * 100) / 100 + " " + UNITS[i];
        }

        // 运行命令行命令
        public static async Task<string> RunCmdAsync(string command)
        {
            var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (var process = Process.Start(processInfo))
            {
                using (var reader = process.StandardOutput)
                {
                    return await reader.ReadToEndAsync();
                }
            }
        }
        public static string RunCmd(string command)
        {
            var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
            {
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                Verb = "runas" // 强制以管理员模式运行
            };

            try
            {
                using (var process = new Process { StartInfo = processInfo })
                {
                    process.Start();

                    // 读取标准输出
                    string output = process.StandardOutput.ReadToEnd();

                    // 读取标准错误（如果有）
                    string error = process.StandardError.ReadToEnd();

                    process.WaitForExit();

                    if (!string.IsNullOrEmpty(error))
                    {
                        Console.Error.WriteLine("Error: " + error);
                    }

                    return output;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failed to run command as administrator: " + ex.Message);
                return string.Empty;
            }
        }

        
    }
}
